<template lang="pug">
.view.cp-con-data-org.fix-flex-pos
  el-row(:gutter="20")
    el-col(:span="12")
      el-card.left-card(v-loading="leftLoading")
        .card-header(slot="header")
          span 公司基本信息
          i.right-btn.el-icon-edit(type="text", @click="leftEditing = true", v-show="!leftEditing")
        .card-body
          el-form(label-position="right", label-width="80px", :model="leftForm", :rules="rules", ref="leftForm")
            el-form-item(label="公司名称")
              el-input(v-model="leftForm.name", :disabled="!leftEditing")
            el-form-item(label="联系电话", prop="contactNo")
              el-input(v-model="leftForm.contactNo", :disabled="!leftEditing")
            el-form-item(label="传真", prop="fax")
              el-input(v-model="leftForm.fax", :disabled="!leftEditing")
            el-form-item(label="通讯地址")
              el-input(v-model="leftForm.address", :disabled="!leftEditing")
            el-form-item(label="邮政编码", prop="zip")
              el-input(v-model="leftForm.zip", :disabled="!leftEditing")
            el-form-item(label="官网", prop="website")
              el-input(v-model="leftForm.website", :disabled="!leftEditing")
            el-form-item(label="公司简介")
              el-input(v-model="leftForm.description", type="textarea", :rows="4", :disabled="!leftEditing")
          .button-wrap
            el-button(type="primary", @click="leftSubmit", v-show="leftEditing") 确定
            el-button(@click="leftCancle", v-show="leftEditing") 取消
    el-col(:span="12")
      el-card.right-card(v-loading="rightLoading")
        .card-header(slot="header")
          span 公司组织架构
          i.right-btn.el-icon-edit(type="text", @click="rightEdit", v-show="!rightEditing")
        .card-body
          el-tree.tree-warp(
            :data="rightData"
            node-key="nodeInfo"
            :props="{children: 'subDepts'}"
            default-expand-all,
            :expand-on-click-node="!rightEditing")
            .custom-tree(slot-scope="{ node, data }")
              span
                span(v-show="!rightEditing") {{ data.deptName }}
                el-input(v-show="rightEditing",
                  placeholder="部门名称",
                  v-model="data.deptName",
                  :disabled="data.nodeInfo.split('-').length == 1")
                span.ml(v-show="!rightEditing", v-if="data.nodeInfo.split('-').length > 1") {{ data.deptCode }}
                el-input.ml(v-show="rightEditing",
                  placeholder="部门编码",
                  v-model="data.deptCode",
                  v-if="data.nodeInfo.split('-').length > 1")
              span(v-show="rightEditing")
                i.el-icon-plus.icon-act(
                  v-show="data.nodeInfo.split('-').length < 3",
                  @click="() => addNode(data)")
                i.el-icon-delete.icon-act(
                  v-show="data.nodeInfo.split('-').length > 1",
                  @click="() => removeNode(node, data)")
          .button-wrap
            el-button(type="primary", @click="rightSubmit", v-show="rightEditing") 确定
            el-button(@click="rightCancel", v-show="rightEditing") 取消
</template>

<script>
import { mapGetters } from 'vuex';
import { deepCopy } from '@/utils';
import ConfigApi from '@/api/config';

const phoneReg = /^((0\d{2,3}-\d{7,8})|(1[34578]\d{9}))$/;
const faxReg = /^(0\d{2,3}-\d{7,8})$/;
const urlReg = /^(?=^.{3,255}$)(http(s)?:\/\/)?(www\.)?[a-zA-Z0-9][-a-zA-Z0-9]{0,62}(\.[a-zA-Z0-9][-a-zA-Z0-9]{0,62})+(:\d+)*(\/\w+\.\w+)*$/;


export default {
  name: 'condataorg',
  data() {
    return {
      leftLoading: true,
      leftEditing: false,
      leftForm: {},
      leftFormBackUp: {},
      rightLoading: true,
      rightEditing: false,
      rightData: [{
        nodeInfo: '1',
        deptName: '',
        updateUser: null,
        subDepts: []
      }],
      rules: {
        contactNo: [
          { message: '请输入正确的联系方式', trigger: 'blur', pattern: phoneReg }
        ],
        fax: [
          { message: '请输入正确的传真号码', trigger: 'blur', pattern: faxReg }
        ],
        zip: [
          { len: 6, message: '邮编长度为6个字符', trigger: 'blur' }
        ],
        website: [
          { message: '请输入正确的网址', trigger: 'blur', pattern: urlReg }
        ]
      },
    };
  },
  computed: {
    ...mapGetters(['employeeId'])
  },
  created() {
    this.rightData[0].updateUser = this.employeeId;
    // 缓存编辑数据
    this.rightCache = [];
  },
  mounted() {
    // 取得公司详情
    this.loadCompanyDetail();
    // 取得部门详情
    this.loadDepartmentDetail();
  },
  methods: {
    loadCompanyDetail() {
      ConfigApi.getCompanyDetail().then((res) => {
        if (res.status === 0) {
          this.leftForm = res.obj;
          this.leftFormBackUp = deepCopy(this.leftForm);
        } else {
          this.$message.error(res.comment);
        }
        this.leftLoading = false;
      }).catch((error) => {
        this.leftLoading = false;
        console.log(JSON.stringify(error));
      });
    },

    // 处理部门详情
    dealDepartmentDetail(data) {
      // 根节点
      data.nodeInfo = '1';
      data.updateUser = this.employeeId;
      this.dealChildren(data.subDepts, data.nodeInfo);
    },

    // 处理children的nodeInfo
    dealChildren(array, prevPosi) {
      const user = this.employeeId;
      if (array && array.length) {
        array.forEach((item, index) => {
          const posi = `${prevPosi}-${index + 1}`;
          item.nodeInfo = posi;
          item.updateUser = user;
          this.dealChildren(item.subDepts, posi);
        });
      }
    },

    loadDepartmentDetail() {
      ConfigApi.getDepartmentsDetail().then((res) => {
        if (res.status === 0) {
          this.dealDepartmentDetail(res.obj);
          this.rightData = [res.obj];
        } else {
          this.$message.error(res.comment);
        }
        this.rightLoading = false;
      }).catch((error) => {
        this.rightLoading = false;
        console.log(JSON.stringify(error));
      });
    },

    leftSubmit() {
      this.$refs.leftForm.validate((valid) => {
        if (!valid) {
          return false;
        }
        const params = {
          ...this.leftForm,
          updateUser: this.employeeId
        };
        this.leftLoading = true;
        ConfigApi.updateCompanyDetail(params).then((res) => {
          if (res.status === 0) {
            this.leftFormBackUp = deepCopy(this.leftForm);
            this.leftEditing = false;
            this.$message({ message: '保存成功', type: 'success' });
            if (this.rightData && this.rightData[0]) {
              this.rightData[0].deptName = this.leftForm.name;
            }
          } else {
            this.$message.error(res.comment || '保存失败');
          }
          this.leftLoading = false;
        }).catch((error) => {
          this.$message.error('网络不给力，请稍后再试');
          this.leftLoading = false;
          console.log(JSON.stringify(error));
        });
      });
    },
    leftCancle () {
      this.leftForm = deepCopy(this.leftFormBackUp);
      this.leftEditing = false;
    },

    rightEdit() {
      this.rightCache = JSON.parse(JSON.stringify(this.rightData));
      this.rightEditing = true;
    },

    volidData(data) {
      if (data.subDepts && data.subDepts.length) {
        data.subDepts.forEach((dept) => {
          if (!dept.deptName) {
            this.$message.error('部门名称不能为空');
            this.hasEmpty = true;
            return false;
          }
          if (!dept.deptCode) {
            this.$message.error('部门编码不能为空');
            this.hasEmpty = true;
            return false;
          }
          this.volidData(dept);
        });
      }
    },

    rightSubmit() {
      this.hasEmpty = false;
      this.volidData(this.rightData[0]);
      if (this.hasEmpty) {
        return false;
      }
      this.rightLoading = true;
      const params = this.rightData[0];
      ConfigApi.updateDepartmentsDetail(params).then((res) => {
        if (res.status === 0) {
          this.dealDepartmentDetail(res.obj);
          this.rightData = [res.obj];
          this.rightLoading = false;
          this.rightEditing = false;
          this.$message({ message: '保存成功', type: 'success' });
        } else {
          this.$message.error(res.comment || '保存失败');
          this.rightLoading = false;
        }
      }).catch((error) => {
        this.$message.error('网络不给力，请稍后再试');
        this.rightLoading = false;
        console.log(JSON.stringify(error));
      });
    },

    rightCancel() {
      this.rightData = this.rightCache;
      this.rightEditing = false;
    },

    addNode(data) {
      let nodeInfo = '';
      let len = 0;
      if (data.subDepts) {
        len = data.subDepts.length;
      }
      if (len > 0) {
        const last = data.subDepts[len - 1].nodeInfo;
        const arr = last.split('-');
        const prev = arr[arr.length - 1];
        nodeInfo = `${data.nodeInfo}-${Number(prev) + 1}`;
      } else {
        nodeInfo = `${data.nodeInfo}-1`;
      }
      const newChild = { nodeInfo, updateUser: this.employeeId, subDepts: [] };
      if (!data.subDepts) {
        this.$set(data, 'subDepts', []);
      }
      data.subDepts.push(newChild);
    },

    removeNode(node, data) {
      const parent = node.parent;
      const subDepts = parent.data.subDepts || parent.data;
      const index = subDepts.findIndex(d => d.nodeInfo === data.nodeInfo);
      subDepts.splice(index, 1);
    },
  }
};
</script>

<style lang="sass">
@import "../../../styles/utils"
.cp-con-data-org
  overflow-x: hidden
  overflow-y: auto
  background: $THEMECOLOR
  height: 100%
  padding: 0 20px 10px
  .el-row, .el-col.el-col-12
    height: 100%
  .left-card, .right-card
    height: 100%
  .el-card
    box-shadow: none
  .el-card__header
    background-color: #F2F2F2
  .el-card__body
    height: calc(100% - 58px)
    overflow: auto
  .card-header
    text-align: center
    position: relative
    .right-btn
      position: absolute
      right: 0
      top: 50%
      font-size: 20px
      margin-top: -10px
      cursor: pointer
      &:hover
        color: #5D9BFB
  .button-wrap
    text-align: center
  .tree-warp
    margin-bottom: 15px
  .el-tree-node__content
    height: 34px
  .el-tree-node:focus>.el-tree-node__content, .el-tree-node__content:hover
    background-color: transparent
  .custom-tree
    flex: 1
    display: flex
    align-items: center
    justify-content: space-between
    font-size: 14px
    padding-right: 8px
    height: 32px
    line-height: 32px
    .el-input
      max-width: 150px
    .icon-act
      font-size: 16px
      font-weight: 500
      cursor: pointer
      margin-left: 3px
      margin-right: 3px
      &:hover
        color: #5D9BFB
    .ml
      margin-left: 14px
</style>
